<?php 
defined('IN_IXDCW') or exit('Access Denied');

class CoshopModule extends BasicModule {

	/** @var 模块id */
	private $_moduleid;

	/** @var 条目ID */
	private $_itemid;

	/** @var string 表格 */
	private $_table;

	/** @var string 表格数据 */
	private $_tableData;

	/** @var 是否内容分表 */
	private $_split;

	/** @var array 可用字段 */
	private $_fields;

	/**
	 * constructor
	 * @param $moduleid
	 */
	function __construct($moduleid) {
		parent::__construct();
		global $table, $table_data, $MOD;
		$this->_moduleid  = $moduleid;
		$this->_table     = $table;
		$this->_tableData = $table_data;
		$this->_split     = $MOD['split'];;
		$this->_fields     = array('arbid','arcid','amid','catid','areaid','typeid','level',
            'introduce','model','price','thumb','thumb1','thumb2','thumb3',
            'tag','status','hits','username','editor','addtime','adddate','edittime',
			'editdate','ip','template','linkurl','filepath','note','company',
            'truename','mobile','address','email','fax','pr_type','stop'
            ,'pre_project','small_pre','team_pre','discount','kin','prompt','title','project','zuobiao','discount1','discount2','discount3','prompt1');
    }

	public function setItemid($itemid) {
		$this->_itemid = $itemid;
	}

	public function getItemid() {
		return $this->_itemid;
	}

	public function getFields() {
		return $this->_fields;
	}

	/**
	 * 是否通过插入检测
	 * @param $post
	 * @return bool
	 */
	function pass($post) {
		global $DT_TIME, $MOD;
		if(!is_array($post)) return false;
		if(!$post['catid']) return $this->err(lang('message->pass_cate'));
		if(strlen($post['title']) < 3) return $this->err(lang('message->pass_title'));
		if($post['totime']) {
			if(!is_date($post['totime'])) return $this->err(lang('message->pass_date'));
			if(strtotime($post['totime'].' 23:59:59') < $DT_TIME) return $this->err(lang('message->pass_todate'));
		}
		return true;
	}

	/**
	 * 设置符合内容的值
	 * @param $post
	 * @return array|mixed
	 */
	function set($post) {

		global $MOD, $DT_TIME, $DT_IP, $TYPE, $_username, $r;
		$post['editor'] = $_username;
		$post['addtime'] = (isset($post['addtime']) && $post['addtime']) ? strtotime($post['addtime']) : $DT_TIME;
		$post['adddate'] = timetodate($post['addtime'], 3);
		$post['edittime'] = $DT_TIME;
		$post['editdate'] = timetodate($post['edittime'], 3);
		$post['price'] = dround($post['price']);
		$post['title'] = trim($post['title']);
		$post['content'] = stripslashes($post['content']);
		if($MOD['clear_link']) $post['content'] =Post::clearLink($post['content']);
		if($MOD['save_remotepic']) $post['content'] = Post::saveRemote($post['content']);
		if($MOD['introduce_length']) $post['introduce'] = addslashes(Post::intro($post['content'], $MOD['introduce_length']));
        if ($post['arbid'][0]){
            foreach($post['arbid'] as $v){if(!preg_match("/^\d*$/",$v)){$post['arbid']='';}}
            sort($post['arbid']);
            $post['arbid'] = implode(',',$post['arbid']);
            $sql = 'select distinct(acid) from xd_auto_model where arbid in ('.$post['arbid'].')';
            $acid = $this->_db->getAll($sql);
            $level = PCache::read('autoCategory-level.php');
            foreach($acid as $v){
                if($v['acid'] != 0){
                    $post['acid'][] = $v['acid'];
                    $post['acid'][] = $level[$v['acid']]['parentid'];
                }
            }
            $post['acid'] = array_flip(array_flip($post['acid']));
            sort($post['acid']);
            $post['acid'] = implode(',',$post['acid']);
        }else{
            $post['arbid']='';
            $post['arcid']='';
            $post['amid']='';
        }

        if ($post['arcid'] && $post['arbid']){
            foreach($post['arcid'] as $v){if(!preg_match("/^\d*$/",$v)){$post['arcid']='';}}
            sort($post['arcid']);
            $post['arcid'] = implode(',',$post['arcid']);
        }else{
            $post['arcid']='';
            $post['amid']='';
        }
        if ($post['arcid'] && $post['arbid'] && $post['amid']){
            foreach($post['amid'] as $v){if(!preg_match("/^\d*$/",$v)){$post['amid']='';}}
            sort($post['amid']);
            $post['amid'] = implode(',',$post['amid']);
        }else{
            $post['amid']='';
        }
		if($this->_itemid) {
			// 处理新传入的img
			$r   = $this->getOne();
			$post['editor'] = $_username;
		} else {
			$post['ip']       = $DT_IP;
		}
		if(!defined('DT_ADMIN')) {
			$content = $post['content'];
			unset($post['content']);
			$post = Str::htmlSpecialChars($post);
			$post['content'] = Str::safe($content);
		}
		$post['content'] = addslashes($post['content']);

		return $post;
	}

	/**
	 * 获取一条数据
	 * @return array|void
	 */
	function getOne() {
		$r = $this->_db->getOne("SELECT * FROM {$this->_table} WHERE itemid=$this->_itemid");
		if($r) {
			$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
			$t = $this->_db->getOne("SELECT content FROM {$content_table} WHERE itemid=$this->_itemid");
			$r['content'] = $t['content'];
			return $r;
		} else {
			return array();
		}
	}

	/**
	 * 获取列表
	 * @param string $condition
	 * @param string $order
	 * @param string $cache
	 * @return array
	 */
	function getList($condition = 'status=3', $order = 'edittime DESC', $cache = '') {
		global $MOD,$kw,$items;
		$num = $this->_db->count($this->_table, $condition, $cache);
		$items=$num;
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($num);
		$sql = "SELECT * FROM {$this->_table}";
		$sql .= $condition ? " WHERE {$condition}" : '';
		$sql .= $order ? " ORDER BY {$order}" : '';
		$sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$lists = $catids = $CATS = array();
		$result = $this->_db->query($sql, $cache);
		if($kw) {
			$replacef = explode(' ', $kw);
			$replacet = array_map('highlight', $replacef);
		}
		while($r = $this->_db->fetchArray($result)) {
			$r['alt'] = $r['title'];
			$r['title'] = set_style($r['title'], $r['style']);
			$r['userurl'] = userurl($r['username']);
			if(strpos($r['linkurl'], '://') === false){
			$r['linkurl'] = $MOD['linkurl'].$r['linkurl'];
			}
			$catids[$r['catid']] = $r['catid'];
			if($kw) $r['title'] = str_replace($replacef, $replacet, $r['title']);
			$lists[] = $r;
		}
		if($catids) {
			$result = $this->_db->query("SELECT catid,catname,linkurl FROM {$this->_db->pre}category WHERE catid IN (".implode(',', $catids).")");
			while($r = $this->_db->fetchArray($result)) {
				$CATS[$r['catid']] = $r;
			}
			if($CATS) {
				foreach($lists as $k=>$v) {
					$lists[$k]['catname'] = $v['catid'] ? $CATS[$v['catid']]['catname'] : '';
					$lists[$k]['caturl'] = $v['catid'] ? $MOD['linkurl'].'?catid='.$v['catid'] : '';
				}
			}
		}
		return $lists;
	}

	/**
	 * @param $post
	 * @return int|string
	 */
	function add($post) {
		global $MOD,$_userid;

		$post = $this->set($post);
		$this->_db->query(Sql::insert($this->_table, $post, $this->_fields));
		$this->_itemid = $this->_db->insertId();
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
		$this->_db->query("INSERT INTO {$content_table} (itemid,content) VALUES ('$this->_itemid', '$post[content]')");
		$this->update($this->_itemid, $post, $post['content']);
		ThumbUpload::clearPicture($this->_moduleid.'_thumb', $post['thumb'], '', $_userid);
		EditorUpload::clearDiff($post['content'], '', $_userid);
		return $this->_itemid;
	}

	/**
	 * 编辑
	 * @param $post
	 * @return bool
	 */
	function edit($post) {
		global $r,$_userid;
		$this->delete($this->_itemid, false);
		$post = $this->set($post);
		$this->_db->query(Sql::update($this->_table, $post, "itemid={$this->_itemid}", '', $this->_fields));
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
	    $this->_db->query(Sql::update($content_table,"content='$post[content]'","itemid=$this->_itemid"));
		$this->update($this->_itemid, $post, $post['content']);
		ThumbUpload::clearPicture($this->_moduleid.'_thumb', $post['thumb'], $r['thumb'], $_userid);
		EditorUpload::clearDiff($post['content'], $r['content'], $_userid);
		return true;
	}



	/**
	 * 更新
	 * @param        $itemid
	 * @param array  $item
	 * @param string $content
	 */
	function update($itemid, $item = array(), $content = '') {
		global $TYPE;
		$update = '';
		$item or $item = $this->_db->getOne("SELECT * FROM {$this->_table} WHERE itemid=$itemid");
		$keyword = $item['title'].','.($item['tag'] ? $item['tag'].',' : '').$TYPE[$item['typeid']].','.strip_tags(cat_pos(get_cat($item['catid']), ','));
		if($keyword != $item['keyword']) {
			$keyword = str_replace("//", '', addslashes($keyword));
			$update .= ",keyword='$keyword'";
		} else {
			$keyword = str_replace("//", '', addslashes($keyword));
		}
		$item['itemid'] = $itemid;
        $linkurl = $item['islink'] ? $item['linkurl'] : url('shop/show', 'itemid='.$item['itemid']);
		if($linkurl != $item['linkurl']) $update .= ",linkurl='$linkurl'";

		$member = $item['username'] ? userinfo($item['username']) : array();
		if($member) {
			$item['vip'] = $member['vip'];
			foreach(array('groupid', 'vip','company','truename','mobile','address','qq','msn','ali','skype') as $v) {
				if($item[$v] != $member[$v]) $update .= ",$v='".addslashes($member[$v])."'";
			}
			if($item['email'] != $member['mail']) $update .= ",email='$member[mail]'";
		}
		if($update) $this->_db->query(Sql::update($this->_table,"".(substr($update, 1))."","itemid=$itemid"));
		//$sorttime = $this->getSorttime($item['edittime'], $item['vip']);

	}

	/**
	 * 回收站
	 * @param $itemid
	 * @return bool
	 */
	function recycle($itemid) {
		if(is_array($itemid)) {
			foreach($itemid as $v) { $this->recycle($v); }
		} else {
			$this->_db->query(Sql::update($this->_table,"status=0","itemid=$itemid"));
			//$this->_db->query(Sql::update($this->_table.'_search',"status=0","itemid=$itemid"));
			$this->delete($itemid, false);
			return true;
		}
	}

	/**
	 * 还原
	 * @param $itemid
	 * @return bool
	 */
	function restore($itemid) {
		global $module, $MOD;
		if(is_array($itemid)) {
			foreach($itemid as $v) { $this->restore($v); }
		} else {
			$this->_db->query(Sql::update($this->_table,"status=3","itemid=$itemid"));
			//$this->_db->query(Sql::update($this->_table.'_search',"status=3","itemid=$itemid"));
			return true;
		}
	}

	/**
	 * 删除条目
	 * @param      $itemid
	 * @param bool $all
	 */
	function delete($itemid, $all = true) {
		global $MOD;
		if(is_array($itemid)) {
			foreach($itemid as $v) {
				$this->delete($v, $all);
			}
		} else {
			$this->_itemid = $itemid;
			$r = $this->getOne();
			if($all) {
				$userid = get_user($r['username']);
				if ($r['thumb']) PictureUpload::deletePicture($r['thumb'], $userid);
				if ($r['content']) EditorUpload::clearDiff('', $r['content'], $userid);
				$this->_db->query(Sql::delete($this->_table,"itemid=$itemid"));
			//$this->_db->query(Sql::delete($this->_table."_search","itemid=$itemid"));
				$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
				$this->_db->query(Sql::delete($content_table,"itemid=$itemid"));
				if($r['username'] && $MOD['credit_del']) {
					credit_add($r['username'], -$MOD['credit_del']);
					credit_record($r['username'], -$MOD['credit_del'], 'system', lang('my->credit_record_del', array($MOD['name'])), 'ID:'.$this->_itemid);
				}
			}
		}
	}

	/**
	 * 检测
	 * @param $itemid
	 * @return bool
	 */
	function check($itemid) {
		global $_username, $DT_TIME, $MOD;;
		if(is_array($itemid)) {
			foreach($itemid as $v) { $this->check($v); }
		} else {
			$this->_itemid = $itemid;
			$item = $this->getOne();
			if($MOD['credit_add'] && $item['username'] && $item['hits'] < 1) {
				credit_add($item['username'], $MOD['credit_add']);
				credit_record($item['username'], $MOD['credit_add'], 'system', lang('my->credit_record_add', array($MOD['name'])), 'ID:'.$this->_itemid);
			}
			$editdate = timetodate($DT_TIME, 3);
			$this->_db->query(Sql::update($this->_table,"status=3,hits=hits+1,editor='$_username',edittime=$DT_TIME,editdate='$editdate'","itemid=$itemid"));
			$sorttime = $this->getSorttime($DT_TIME, $item['vip']);
		//	$this->_db->query(Sql::update($this->_table.'_search',"status=3,sorttime='$sorttime'","itemid=$itemid"));
			return true;
		}
	}

	/**
	 * 未通过审核
	 * @param $itemid
	 * @return bool
	 */
	function reject($itemid) {
		global $_username, $DT_TIME;
		if(is_array($itemid)) {
			foreach($itemid as $v) { $this->reject($v); }
		} else {
			$this->_db->query(Sql::update($this->_table,"status=1,editor='$_username'","itemid=$itemid"));
			//$this->_db->query(Sql::update($this->_table.'_search',"status=1","itemid=$itemid"));
			return true;
		}
	}

	function expire($condition = '') {
		global $DT_TIME;
		$result = $this->_db->query("SELECT itemid FROM {$this->_table} WHERE status=3 AND totime>0 AND totime<$DT_TIME $condition");
		while($r = $this->_db->fetchArray($result)) {
			$itemid = $r['itemid'];
			$this->_db->query(Sql::update($this->_table,"status=4","itemid=$itemid"));
			//$this->_db->query(Sql::update($this->_table.'_search',"status=4","itemid=$itemid"));
		}
	}

	/**
	 * 清空
	 * @param string $condition
	 */
	function clear($condition = 'status=0') {
		$result = $this->_db->query("SELECT itemid FROM {$this->_table} WHERE $condition ");
		while($r = $this->_db->fetchArray($result)) {
			$this->delete($r['itemid']);
		}
	}

	/**
	 * 随机获取一张商家图片
	 * @param string $userid
	 */
	public static function getPic($userid) {
		global $db;
		return $db->getVar("select distinct thumb from {$db->getPre()}business_picture where userid=$userid order by rand() ");
	}

	/**
	 * 级别设置
	 * @param $itemid
	 * @param $level
	 */
	function level($itemid, $level) {
		$itemids = is_array($itemid) ? implode(',', $itemid) : $itemid;
		$this->_db->query(Sql::update($this->_table,"level=$level","itemid IN ($itemids)"));
	}

	function type($itemid, $typeid) {
		$itemids = is_array($itemid) ? implode(',', $itemid) : $itemid;
		$this->_db->query(Sql::update($this->_table,"typeid=$typeid","itemid IN ($itemids)"));
	}

	/**
	 * 刷新
	 * @param $itemid
	 */
	function refresh($itemid) {
		global $DT_TIME;
		$editdate = timetodate($DT_TIME, 3);
		if(is_array($itemid)) {
			foreach($itemid as $v) { $this->refresh($v); }
		} else {
			$this->_db->query(Sql::update($this->_table,"edittime='$DT_TIME',editdate='$editdate'","itemid=$itemid"));
			$this->_itemid = $itemid;
			$item = $this->_db->getOne("SELECT vip FROM {$this->_table} WHERE itemid=$itemid");
			$sorttime = $this->getSorttime($DT_TIME, $item['vip']);
			$this->_db->query(Sql::update($this->_table.'_search',"sorttime='$sorttime'","itemid=$itemid"));
		}
	}

	function getSorttime($edittime, $vip) {
		$sorttime = timetodate($edittime, 'Y-m-d').' '.sprintf('%02d', $vip).':'.timetodate($edittime, 'H:i');
		return strtotime($sorttime);
	}

}
?>